package com.qtenv.datasync.api.daiao;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

import java.util.Map;

public class DaiAoApi {

    private final static String host = "https://zcsw.izarinsight.com";
    private final static String account = "zc";
    private final static String password = "zc@12345";

    private static JSONObject post(String url, Map<String, Object> paramMap) {
        return post(url, paramMap, true);
    }

    private static JSONObject postNoHeader(String url, Map<String, Object> paramMap) {
        return post(url, paramMap, false);
    }

    private static JSONObject post(String url, Map<String, Object> paramMap, boolean header) {
        HttpRequest post = HttpUtil.createPost(host + url);

        if (header) {
            post.header("Authorization", getToken());
        }

        String result = post.contentType("application/json").body(JSONUtil.toJsonStr(paramMap)).execute().body();
        return JSONUtil.parseObj(result);
    }

    private static JSONObject get(String url, String body) {
        HttpRequest get = HttpUtil.createGet(url).header("Authorization", getToken());
        String result = get.body(body).execute().body();
        return JSONUtil.parseObj(result);
    }

    private static String getToken() {
        String result = HttpUtil.post(host + "/pluginsToken/getToken", "account=" + account + "&password=" + password);
        return JSONUtil.parseObj(result).getStr("Authorization");
    }

    /**
     * 获取设备档案
     *
     * @param body
     * @return
     */
    public static JSONObject meters(String body) {
        return get(host + "/plugins/meters/information", body);
    }

    /**
     * 获取设备数据
     *
     * @param meterCode
     * @param startTime
     * @param endTime
     * @return
     */

    public static JSONArray historyData(String meterCode, String startTime, String endTime) {
        HttpRequest get = HttpUtil.createGet(host + "/plugins/measVals/his/information").header("Authorization", getToken());
        String result = get.body("meterNumber=" + meterCode + "&startTime=" + startTime + "&endTime=" + endTime).execute().body();
        return JSONUtil.parseArray(result);
    }

    public static void main(String[] args) {
//        System.out.println(getToken());
        System.out.println(meters("meterUse=water&usageType=bigmeter&page=1&limit=30"));
//        System.out.println(historyData("861282044325159", "2023-12-06 00:00:00", "2023-12-06 23:59:59"));
    }
}
